<?php

class RegistroController extends BaseController {

	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/

	public function index()
	{
		$user= Auth::user();
		return View::make('contents.registro', compact('user'));
	}
	
	public function store()
	{
		
		$validator = Validator::make($data = Input::all(), User::$rules);
		
		if ($validator->fails())
		{
			return Redirect::back()->withErrors($validator)->withInput();
		}
		
		$user = new User();
		$user->fill($data);
		$user->password=Hash::make($user->password);	
		$user->save();
		
		$user->roles()->sync(array(Rol::find(2)->id));
		
		Auth::login($user,true);
		
		return Redirect::route('home');
	}
	
	public function loginWithFacebook() {
	
		
		// get data from input
		$code = Input::get( 'code' );
	
		// get fb service
		$fb = OAuth::consumer( 'Facebook' );
		
		// check if code is valid
	
		// if code is provided get user data and sign in
		if ( !empty( $code ) ) {
	
			// This was a callback request from facebook, get the token
			$token = $fb->requestAccessToken( $code );
	
			// Send a request with it
			$result = json_decode( $fb->request( '/me' ), true );
	
			$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
			//echo $message. "<br/>";
	
			//Var_dump
			//display whole array().
			//dd($result);
			//return Redirect::back();
			$fbuser = User::where('facebook_id','=',$result['id'])->first();
			
			if($fbuser){
				Auth::login($fbuser,true);
			} else if($fbuser = User::where('email','=',$result['email'])->first()){ 
				$fbuser->facebook_id=$result['id'];
				Auth::login($fbuser,true);
			} else {
				$user = new User();
				$user->username=$result['name'];
				$user->facebook_id=$result['id'];
				$user->email=$result['email'];
				$user->save();
				$user->roles()->sync(array(Rol::find(2)->id));
				
				Auth::login($user,true);
			}
			
			return Redirect::route('home');
			
		}
		// if not ask for permission first
		else {
			// get fb authorization
			$url = $fb->getAuthorizationUri();
	
			// return to facebook login url
			return Redirect::to( (string)$url );
		}
	
	}

}